package com.xinqiupark.technology.ui.activity;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.LruCache;
import android.widget.Button;
import android.widget.ImageView;

import com.xinqiupark.technology.R;

import butterknife.BindView;
import butterknife.ButterKnife;

public class LruCacheActivity extends AppCompatActivity {

    @BindView(R.id.image)
    ImageView mImageView;
    @BindView(R.id.btn_load)
    Button mBtnLoad;

    private final static String TAG=LruCacheActivity.class.getSimpleName();

    private LruCache<String,Bitmap> mMemoryCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lru_cache);
        ButterKnife.bind(this);

        //获取虚拟机提供最大内存
        final int maxMemory= (int) (Runtime.getRuntime().maxMemory()/1024);

        // 2. 设置LruCache缓存的大小 = 一般为当前进程可用容量的1/8
        final int cacheSize=maxMemory/8;

        mMemoryCache=new LruCache<String,Bitmap>(cacheSize)
        {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getByteCount()/1024;//转化为kb
            }
        };


        mBtnLoad.setOnClickListener(view->{
            // 加载图片 ->>分析1
            loadBitmap("test");
        });
    }


    /**
     * 加载图片
     */
    private void loadBitmap(String key) {
        final Bitmap bitmap = mMemoryCache.get(key);

        if(bitmap!=null)
        {
            Log.d(TAG, "从缓存中加载图片 ");
            mImageView.setImageBitmap(bitmap);
        }
        else
        {
            Log.d(TAG, "从数据源（本地）中加载: ");
            mImageView.setImageResource(R.drawable.dog);

            //加入缓存中
            // 注：在添加到缓存前，需先将资源文件构造成1个BitMap对象（含设置大小）
            Resources resources=getResources();
            final Bitmap bm = BitmapFactory.decodeResource(resources, R.drawable.dog);

            //获取图片的宽度高度
            final int width = bm.getWidth();
            final int height=bm.getHeight();


            // 设置想要的大小
            int newWidth = 80;
            int newHeight = 80;
            // 计算缩放比例
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;

            Matrix matrix=new Matrix();
            matrix.postScale(scaleWidth,scaleHeight);
            final Bitmap bitmap_s  = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);

            if (mMemoryCache.get(key) == null) {
                mMemoryCache.put(key,bitmap_s);
                Log.d(TAG, "添加到缓存: " + (mMemoryCache.get(key)));
            }
        }
    }
}
